//
//  NSString+Tools.m
//  VR
//
//  Created by hxp on 16/3/13.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "NSString+Tools.h"
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (Tools)


/**
 *  判断字符串里是否含有表情
 */
+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}



+(NSMutableAttributedString *)content:(NSString *)title name:(NSString *)name
{
    NSString *string = [NSString stringWithFormat:@"%@：%@",title,name];
    NSMutableAttributedString *maString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange rang =  [string  rangeOfString:@"："];
    [maString  addAttribute:NSForegroundColorAttributeName  value:[UIColor lightGrayColor] range:NSMakeRange(0, rang.location + 1)];
    [maString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(rang.location + 1, maString.length - rang.location -1)];
    return maString;
}

+(NSString *)payState:(NSString *)state
{
    if ([state isEqualToString:@"0"]) {
        return @"未生效";
    }else if ([state isEqualToString:@"1"]){
        return @"未付款";
    }else if ([state isEqualToString:@"2"]){
        return @"已付款";
    }else if ([state isEqualToString:@"3"]){
        return @"完成";
    }else{
        return @"取消";
    }
}
+(NSString *)dateString:(NSString *)time
{
    int t = [time doubleValue] / 1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:t];
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    formater.dateFormat = @"YYYY-MM-dd";
    NSString *dateStr = [formater  stringFromDate:date];
    return dateStr;
}

+(NSString *)timeString:(NSString *)time
{
    int t = [time doubleValue] / 1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:t];
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    formater.dateFormat = @"HH:mm";
    NSString *dateStr = [formater  stringFromDate:date];
    return dateStr;
}


+(NSString *)ageStr:(NSString *)birthday
{
    if (birthday == nil) {
        return @" ";
    }
    NSString *birthdateString = [self dateString:birthday];
    int  birth = [[birthdateString  substringToIndex:4] intValue];
    NSDate *date = [NSDate new];
    NSDateFormatter *formater = [NSDateFormatter new];
    formater.dateFormat = @"YYYY";
    NSString *dateStr = [formater  stringFromDate:date];
    int curDate = [dateStr intValue];
    return [NSString stringWithFormat:@"%d",(curDate - birth)];
    
}


- (CGSize)sizewithFont:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizewithFont:font maxSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)];
}

NSString * MD5Hash(NSString *aString) {
    const char *cStr = [aString UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]];
}

+(NSMutableAttributedString *)titleStr:(NSString *)title content:(NSString *)content font:(UIFont *)font
{
    NSMutableAttributedString *ABstr = nil;
    if (content.length == 0) {
       ABstr = [[NSMutableAttributedString alloc] initWithString:title];
      [ABstr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:122/255.0 green:120/255.0 blue:120/255.0 alpha:1] range:NSMakeRange(0, 4)];
    }else{
        NSString *str = [NSString stringWithFormat:@"%@ %@",title,content];
        ABstr = [[NSMutableAttributedString alloc] initWithString:str];
        [ABstr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:122/255.0 green:120/255.0 blue:120/255.0 alpha:1] range:NSMakeRange(0, 4)];
        [ABstr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:38/255.0 green:37/255.0 blue:37/255.0 alpha:1] range:NSMakeRange(5, ABstr.length - 6)];
    }
    
    [ABstr addAttribute:NSFontAttributeName value:font  range:NSMakeRange(0, ABstr.length)];
    return ABstr;
    
}


+ (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"请输入有效的手机号";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入有效的手机号";
        }
    }
    return nil;
}


//汉字的拼音
- (NSString *)pinyin
{
    NSMutableString *str = [self mutableCopy];
    CFStringTransform(( CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    
    return [str stringByReplacingOccurrencesOfString:@" " withString:@""];
}



/**
 *  @brief  固定电话区号格式化（将形如 01085792889 格式化为 010-85792889）
 *
 *  @return 返回格式化后的号码（形如 010-85792889）
 */
- (NSString*)areaCodeFormat
{
    // 先去掉两边空格
    NSMutableString *value = [NSMutableString stringWithString:[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    
    // 先匹配是否有连字符/空格，如果有则直接返回
    NSString *regex = @"^0\\d{2,3}[- ]\\d{7,8}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    if([predicate evaluateWithObject:value]){
        // 替换掉中间的空格
        return [value stringByReplacingOccurrencesOfString:@" " withString:@"-"];
    }
    
    // 格式化号码 三位区号
    regex = [NSString stringWithFormat:@"^(%@)\\d{7,8}$",[self regex_areaCode_threeDigit]];
    predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if([predicate evaluateWithObject:value]){
        // 插入连字符 "-"
        [value insertString:@"-" atIndex:3];
        return value;
    }
    
    
    // 格式化号码 四位区号
    regex = [NSString stringWithFormat:@"^(%@)\\d{7,8}$",[self regex_areaCode_fourDigit]];
    predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if([predicate evaluateWithObject:value]){
        // 插入连字符 "-"
        [value insertString:@"-" atIndex:4];
        return value;
    }
    
    return nil;
}

/**
 *  @brief  验证固定电话区号是否正确（e.g. 010正确，030错误）
 *
 *  @return 返回固定电话区号是否正确
 */
- (BOOL)isAreaCode
{
    
    NSString *regex = [NSString stringWithFormat:@"^%@|%@$",[self regex_areaCode_threeDigit],[self regex_areaCode_fourDigit]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if([predicate evaluateWithObject:self]){
        return YES;
    }
    
    return NO;
}


/**
 *  @brief  获取三位数区号的正则表达式（三位数区号形如 010）
 */
- (NSString*)regex_areaCode_threeDigit
{
    return @"010|02[0-57-9]";
}
/**
 *  @brief  获取四位数区号的正则表达式（四位数区号形如 0311）
 */
- (NSString*)regex_areaCode_fourDigit
{
    // 03xx
    NSString *fourDigit03 = @"03([157]\\d|35|49|9[1-68])";
    // 04xx
    NSString *fourDigit04 = @"04([17]\\d|2[179]|[3,5][1-9]|4[08]|6[4789]|8[23])";
    // 05xx
    NSString *fourDigit05 = @"05([1357]\\d|2[37]|4[36]|6[1-6]|80|9[1-9])";
    // 06xx
    NSString *fourDigit06 = @"06(3[1-5]|6[0238]|9[12])";
    // 07xx
    NSString *fourDigit07 = @"07(01|[13579]\\d|2[248]|4[3-6]|6[023689])";
    // 08xx
    NSString *fourDigit08 = @"08(1[23678]|2[567]|[37]\\d)|5[1-9]|8[3678]|9[1-8]";
    // 09xx
    NSString *fourDigit09 = @"09(0[123689]|[17][0-79]|[39]\\d|4[13]|5[1-5])";
    
    return [NSString stringWithFormat:@"%@|%@|%@|%@|%@|%@|%@",fourDigit03,fourDigit04,fourDigit05,fourDigit06,fourDigit07,fourDigit08,fourDigit09];
    
}

@end
